import { createRouter, createWebHistory } from 'vue-router';
import UserList from '@/views/system/user/UserList.vue';
import RoleList from '@/views/system/role/RoleList.vue';
import MenuList from '@/views/system/MenuList.vue';
import MainLayout from '@/layouts/MainLayout.vue';
import Dashboard from '@/views/Dashboard.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: MainLayout,
      redirect: '/dashboard',
      children: [
        {
          path: '/dashboard',
          name: 'Dashboard',
          component: Dashboard,
          meta: { title: '数据看板' }
        },
        {
          path: '/system/user',
          name: 'UserList',
          component: UserList,
          meta: { title: '用户管理' }
        },
        {
          path: '/system/role',
          name: 'RoleList',
          component: RoleList,
          meta: { title: '角色管理' }
        },
        {
          path: '/system/menu',
          name: 'MenuList',
          component: MenuList,
          meta: { title: '菜单管理' }
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  
  if (to.path === '/login' && isAuthenticated) {
    next('/')
  } else if (to.path !== '/login' && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router